package com.peter.api.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import com.peter.api.common.ErrorCode;
import com.peter.api.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Author: Peter
 * @Date: 2024-11-07-17:54
 * @Description: Pe
 */
@Configuration
@Slf4j
public class SaTokenConfig implements WebMvcConfigurer {
    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {

            try {
                StpUtil.checkLogin();
            }catch (NotLoginException e){
                log.error("未登录异常"+e);
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
            }
        }))
                .addPathPatterns("/**")
                .excludePathPatterns("/user/doLogin","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"
                        ,"/doc.html/**","/error","/favicon.ico"
                );
    }
}

